<?php

namespace app\api\controller\v2;

use app\api\controller\Common;
use think\Cache;

class Index extends Common
{
	var $modelDb;
	public function _initialize()
	{
		parent::_initialize();
	}
	public function h5url()
	{
		$urlarr = [
			'pay' => APP_URL . '/index.php/index/member/pay',
			'hexiaoquanyi' => APP_URL . '/index.php/index/member/hexiaoquanyi',
			'huiyuanquanyi' => APP_URL . '/index.php/index/member/huiyuanquanyi',
			'jianglijinlist' => APP_URL . '/index.php/index/member/jianglijinlist',
			'shensujilu' => APP_URL . '/index.php/index/member/shensujilu',
			'shensujiemian' => APP_URL . '/index.php/index/member/shensujiemian',
			'myshare' => APP_URL . '/index.php/index/member/share',
			// 'amount' => APP_URL.'/index/member/amount',
			'jifenstat' => APP_URL . '/index.php/index/member/jifen/noheader/1',
			// 'downorder' => tabUrl($downorder,'下单管理'),
			'exchange' => APP_URL . '/index.php/index/member/exchange',
			'myformwork' => APP_URL . '/index.php/index/member/formwork',
			// 'aboutus' => APP_URL.'/index/news/aboutus',
			// 'viplevel' => APP_URL.'/index/news/viplevel',
			// 'guanzhu' => APP_URL.'/index/member/guanzhu',
			// 'favorites' => APP_URL.'/index/member/favorites',
			'setting' => APP_URL . '/index.php/index/setting/index',
			'clientall' => APP_URL . '/index.php/index/client/index',
			'saleafter' => '#',
			'sharerecord' => DEVICE === 'android' ? APP_URL . '/index/member/share_record/noheader/1' : APP_URL . '/index/member/share_record',
			// 'subordclient' => APP_URL.'/index/client/index/type/subord',
			'mysubord' => APP_URL . '/index.php/index/client/mysubord',
			'data_stat' => APP_URL . '/index.php/index/client/data_stat',
			'clue_add' => APP_URL . '/index.php/index/client/clue_add',
			'address' => APP_URL . '/index.php/index/member/address',
			'editpwd' => APP_URL . '/index.php/index/member/editpwd',
			'aboutus' => APP_URL . '/index.php/index/news/aboutus',
			'client_deal_detail' => APP_URL . '/index.php/index/client/order',
		];
		return $this->app_success($urlarr);
	}
	//获取验证码
	public function sendsms()
	{
		// $this->app_error('验证码获取失败');
		if (isset($this->postData['check_phone_unique']) && $this->postData['check_phone_unique'] == 'forget_pwd') {
			$result = $this->validate($this->postData, 'AdminUser.check_phone_unique');
		} elseif (isset($this->postData['check_phone_unique']) && $this->postData['check_phone_unique'] == 'register') {
			$result = $this->validate($this->postData, 'AdminUser.bind_phone_check');
		} else {
			$result = $this->validate($this->postData, 'AdminUser.check_phone');
		}
		if (!isset($this->postData['sign']) || $this->postData['sign'] != md5($this->postData['phone'] . '@nnssm')) {
			return $this->app_error('验证码获取失败');
		}
		if ($result !== true) {
			return $this->app_error($result);
		}
		$status = send_sms($this->postData['phone']);
		if ($status) {
			return $this->app_success(['status' => $status], '发送成功');
		} else {
			return $this->app_error('验证码获取失败，请重新获取！');
		}
	}
	public function forgetpwd()
	{
		$result = $this->validate($this->postData, 'AdminUser.forget_pwd');
		trace($result);
		if ($result !== true) {
			return $this->app_error($result);
		}
		$ids = model("AdminUser")->forget_pwd($this->postData);
		if ($ids) {
			return $this->app_success([], '修改成功');
		} else {
			return $this->app_error();
		}
	}
	public function download()
	{
		if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')) {
			echo '<!doctype html>
            <html>
            <head>
            <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
            <meta charset="utf-8">
            <title>下载中心</title>
            <style>
            *{ margin:0; padding:0;}
            </style>
            </head>

            <body>
            <img src="/public/static/images/downloadyd.png" style="width:100%">
            </body>
            </html>';
			exit();
		} else if (strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strpos($_SERVER['HTTP_USER_AGENT'], 'iPad')) {
			header("location:https://itunes.apple.com/cn/app/%E6%96%AF%E5%AE%B6%E4%BF%B1%E4%B9%90%E9%83%A8/id1330899825?mt=8");
			//echo "苹果下载地址";
			exit();
		} else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Android')) {
			$version = Cache::get("AppVersion");
			$versions = json_decode(json_encode($version), true);
			$i = 0;
			foreach ($versions as $version) {
				$i++;
				if ($i > 1) {
					break;
				}

				$url = APP_URL . "/" . $version['appurl'];
			}
			//$url = "http://a.app.qq.com/o/simple.jsp?pkgname=com.coco3g.mantun";
			header("location:" . $url);
			exit();
		} else {
			$version = Cache::get("AppVersion");
			$versions = json_decode(json_encode($version), true);
			$i = 0;
			foreach ($versions as $version) {
				$i++;
				if ($i > 1) {
					break;
				}

				$url = APP_URL . "/" . $version['appurl'];
			}
			//$url = "http://a.app.qq.com/o/simple.jsp?pkgname=com.coco3g.mantun";
			header("location:" . $url);
			exit();
		}
	}
	//获取版本号
	public function version()
	{
		$version = Cache::get("AppVersion");
		$versions = json_decode(json_encode($version), true);
		$i = 0;
		foreach ($versions as $version) {
			$i++;
			if ($i > 1) {
				break;
			}

			$data = array(
				'number' => $version['number'],
				'version' => $version['version'],
				'updatelog' => $version['log'],
				'code' => $version['code'],
				'appurl' => APP_URL . "/" . $version['appurl'],
			);
		}
		$this->app_success($data);
	}
	public function get_cartype()
	{
		$list = model('Cartype')->list_datad(['pid' => $this->postData['pid'], 'hide' => 0], 1, 100, 'id,title', 'listorder asc,id asc');
		if ($list === false) {
			return $this->app_error(model('Cartype')->getError());
		}
		return $this->app_success($list);
	}
	public function get_car()
	{
		$list = model('Car')->list_datad(['pid' => $this->postData['pid'], 'hide' => 0], 1, 100, 'id,title', 'id asc');
		if ($list === false) {
			return $this->app_error(model('Car')->getError());
		}
		return $this->app_success($list);
	}

	// 获取线索分类
	public function get_client_type()
	{
		$kind = config('CLIENT_KIND');
		if (is_array($kind) && isset($kind)) {
			$str_temp = [];
			$count = 0;
			foreach ($kind as $key => $value) {
				$arr_temp = [
					'id' => $key,
					'value' => $value,
				];
				$str_temp[$count++] = $arr_temp;
			}
			// $returnData = json_encode($str_temp);
			return $this->app_success($str_temp);
		} else {
			return $this->app_error();
		}
	}
	//生成海报图片
	// public function create_image(){
	//     $qrcode = createqr(APP_URL.'/index/index/poster/id/'.$this->postData['formworkid'], 50);
	//     $data = model('Poster')->get_data(['item_id'=>$this->postData['posterid']]);
	//     $save_path1 = '';
	//     $save_path2 = '';
	//     $underimage = str_replace(APP_URL, '', $data['underimage']);
	//     if ($qrcode) {
	//         $image = \think\Image::open(ROOT_PATH.$underimage);
	//         $image_location = explode(',', $data['image_location']);
	//         $save_path1 = '/upload/'.date('Ymd',SYS_TIME).'/'.md5(date('YmdHis').rand(10000, 99999)).'.png';
	//         $image->water(ROOT_PATH.$qrcode,[isset($image_location[0])?$image_location[0]:0, isset($image_location[1])?$image_location[1]:0])->save(ROOT_PATH.$save_path1);
	//     }
	//     if ($this->postData['text']) {
	//         $image = \think\Image::open(ROOT_PATH.$save_path1);
	//         $text_location = explode(',', $data['text_location']);
	//         $save_path2 = '/upload/'.date('Ymd',SYS_TIME).'/'.md5(date('YmdHis').rand(10000, 99999)).'.png';
	//         $image->text($this->postData['text'],ROOT_PATH.'/public/static/fonts/msjh.ttf',$data['font_size']?$data['font_size']:16,$data['font_color']?$data['font_color']:'#ffffff', [isset($text_location[0])?$text_location[0]:0, isset($text_location[1])?$text_location[1]:0])->save(ROOT_PATH.$save_path2);
	//     }
	//     $save_path = $save_path2 ? $save_path2 : $save_path1;
	//     trace($save_path);
	//     return $this->app_success(['thumb'=>APP_URL.$save_path]);
	// }
	public function media_list()
	{
		if ($this->uinfo['roleid'] < 7) {
			return $this->app_success();
		}
		$page = isset($this->postData['page']) ? $this->postData['page'] : 1;
		$where = [];
		if (isset($this->uinfo['userid'])) {
			switch ($this->uinfo['roleid']) {
				case 9:
					$where['userid'] = model('AdminUser')->where('userid', $this->uinfo['puserid'])->value('puserid');
					break;
				case 8:
				case 7:
					$where['userid'] = $this->uinfo['puserid'];
					break;
			}
		}
		$list = model('Media')->list_datad($where, $page, 10);
		if ($list === false) {
			return $this->app_error(model('Media')->getError());
		}
		return $this->app_success($list);
	}

	// 经销商所属省份(常用省份)
	public function province_list()
	{
		$configlist = config('DEALER_PROVINCE');
		$citylist = model('City')->where('depth', '2')->whereIn('title', $configlist)->field('title, code')->select();
		foreach ($citylist as $key => $value) { // 如果有陕西省，将陕西省置顶
			if ($value['title'] == '陕西省') {
				trace($key);
				$temp = $citylist[$key];
				unset($citylist[$key]);
				array_unshift($citylist, $temp);
				break;
			}
		}
		return $this->app_success($citylist);
	}

	// 根据省份code，获取经销商列表
	public function storeList()
	{
		$provinceCode = $this->postData['provinceCode'];
		$list = model('AdminUser')->where('status', 0)->where('roleid', 6)->where('province_code', $provinceCode)->field('userid as storeid,fullname, username')->order('userid asc')->select();
		if ($list === false) {
			return $this->app_error('获取失败');
		}
		return $this->app_success($list);
	}
	public function get_config()
	{
		return $this->app_success(['identity' => array_values(config('IDENTITY'))]);
	}

	public function province_dealer()
	{
		$userid = $this->postData['ownerid'];
		$dealerid = model('AdminUser')->where('userid', $userid)->value('dealerid');
		$data = model('AdminUser')->where('userid', $dealerid)->field('fullname, province_code')->find();
		$cityname = model('City')->where('code', $data['province_code'])->value('title');
		$returndata = [
			'cityname' => $cityname,
			'province_code' => $data['province_code'],
			'dealername' => $data['fullname'],
			'dealerid' => $dealerid
		];
		return $this->app_success($returndata);
	}

	// 获取荣耀会员价格（默认：99元）
	public function get_vip_price()
	{
		$type = isset($this->postData['type']) ? $this->postData['type'] : 0;;
		if ($type == 1) { // 激活2000元购车券
			$data = [
				'vip_price' => config('VIP_PRICE'),
				'title' => '激活优惠券'
			];
			return $this->app_success($data);
		} else {
			$data = [
				'vip_price' => config('VIP_PRICE'),
				'title' => '荣耀会员'
			];
			return $this->app_success($data);
		}
	}

	// 显示二维码
	public function showqr()
	{
		$couponsno = isset($this->postData['couponsno']) ? $this->postData['couponsno'] : 'hellow world!';
		if ($couponsno) {
			showqr(trim($couponsno));
		}
	}

	// 获取汽车品牌列表(一级)
	public function car_brand_list()
	{
		$list = model('Cartype')->where('depth', '1')->order('listorder asc')->field('id, title, thumb')->select();
		return $this->app_success($list);
	}

	// 获取汽车品牌列表(二级)
	public function sub_car_brand_list()
	{
		$list = model('Cartype')->where('pid', $this->postData['id'])->field('id, title, thumb')->select();
		return $this->app_success($list);
	}

	// 获取汽车品牌列表(三级)
	public function m_car_brand_list()
	{
		$list = model('Cartype')->where('pid', $this->postData['id'])->field('id, title, thumb')->select();
		if ($list == null) {
			$list = model('Car')->where('pid', $this->postData['id'])->field('id, title, thumb')->select();
			if ($list == null) {
				$list = [
					'id' => '-1',
					'title' => '无车型-'
				];
			}
		}
		return $this->app_success($list);
	}

	// 根据省份code获取省份名称
	public function get_province_dealcer()
	{
		$province = model('City')->where('pid', '1')->where('code', $this->postData['province_code'])->value('title');
		$dealername = model('AdminUser')->where('userid', $this->postData['storeid'])->value('fullname');
		$returnData = [
			'province' => $province,
			'dealer' => $dealername,
		];
		return $this->app_success($returnData);
	}

	// 轮播图列表
	public function get_lunbo_list()
	{
		$list = model('Lunbo')->field('title, thumb, linkurl')->select();
		return $this->app_success($list);
	}
}
